package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements jakarta.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        jakarta.servlet.Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
//1.
        String url =req.getRequestURL().toString();
        if(url.contains("login")){
            chain.doFilter(req,rep);
            return;
        }

        String token = req.getHeader("token");
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
//            rep.setStatus(HttpStatus.UNAUTHORIZED.value());
            rep.setStatus(401);
            return;
        }
        chain.doFilter(req,rep);
    }

    @Override
    public void destroy() {
        jakarta.servlet.Filter.super.destroy();
    }
}
